import React, { useEffect, useState } from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import { Box, CircularProgress, Typography } from '@mui/material';
import { invoke } from '@tauri-apps/api/core';
import toast from 'react-hot-toast';

// Components
import Layout from './components/Layout';
import ConnectionManager from './pages/ConnectionManager';
import Terminal from './pages/Terminal';
import Settings from './pages/Settings';
import TunnelManager from './pages/TunnelManager';

// Store
import { useAppStore } from './store/appStore';

// Types
import type { AppConfig, ConnectionConfig } from './types/config';

const App: React.FC = () => {
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const { setConfig, setConnections } = useAppStore();

  // 初始化应用
  useEffect(() => {
    const initializeApp = async () => {
      try {
        setIsLoading(true);
        setError(null);

        // 加载应用配置
        try {
          const config: AppConfig = await invoke('get_app_config');
          setConfig(config);
        } catch (err) {
          console.warn('Failed to load app config, using defaults:', err);
          // 使用默认配置
          const defaultConfig: AppConfig = {
            version: '0.1.0',
            app_version: '0.1.0',
            log_level: 'info',
            auto_save_config: true,
            theme: {
              name: 'dark',
              mode: 'dark',
              primary_color: '#007acc',
              secondary_color: '#ff6b35',
              colors: {
                primary: '#007acc',
                secondary: '#ff6b35',
                background: '#1a1a1a',
                surface: '#2a2a2a',
                text: '#ffffff',
              },
            },
            terminal_defaults: {
              font_family: 'SF Mono, Monaco, Consolas, monospace',
              font_size: 14,
              cursor_style: 'block',
              cursor_blink: true,
              scrollback: 10000,
              bell_sound: false,
            },
            security: {
              auto_lock: true,
              auto_lock_timeout: 300,
              lock_timeout_minutes: 5,
              remember_passwords: false,
              encrypt_passwords: true,
              encrypt_config: true,
              clear_clipboard: true,
            },
            recent_connections: [],
            window: {
              width: 1200,
              height: 800,
              default_width: 1200,
              default_height: 800,
              remember_size: true,
              remember_position: true,
            },
          };
          setConfig(defaultConfig);
        }

        // 加载保存的连接
        try {
          const connections = await invoke('get_saved_connections') as ConnectionConfig[];
          setConnections(connections || []);
        } catch (err) {
          console.warn('Failed to load saved connections:', err);
          setConnections([]);
        }

        // 检查是否需要设置主密钥
        try {
          const hasKey = await invoke('has_master_key');
          if (!hasKey) {
            toast('首次使用，请在设置中配置主密钥以保护您的连接信息', {
              icon: '🔐',
              duration: 6000,
            });
          }
        } catch (err) {
          console.warn('Failed to check master key status:', err);
        }

        setIsLoading(false);
      } catch (err) {
        console.error('Failed to initialize app:', err);
        setError(err instanceof Error ? err.message : '应用初始化失败');
        setIsLoading(false);
      }
    };

    initializeApp();
  }, [setConfig, setConnections]);

  // 错误重试
  const handleRetry = () => {
    setError(null);
    window.location.reload();
  };

  // 加载中界面
  if (isLoading) {
    return (
      <Box
        sx={{
          height: '100vh',
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          backgroundColor: 'background.default',
          gap: 2,
        }}
      >
        <CircularProgress size={48} />
        <Typography variant="h6" color="text.secondary">
          正在初始化 RustShell...
        </Typography>
        <Typography variant="body2" color="text.secondary">
          加载配置和连接信息
        </Typography>
      </Box>
    );
  }

  // 错误界面
  if (error) {
    return (
      <Box
        sx={{
          height: '100vh',
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          backgroundColor: 'background.default',
          gap: 2,
          p: 3,
        }}
      >
        <Typography variant="h4" color="error" gutterBottom>
          应用启动失败
        </Typography>
        <Typography variant="body1" color="text.secondary" textAlign="center" sx={{ mb: 2 }}>
          {error}
        </Typography>
        <Box sx={{ display: 'flex', gap: 2 }}>
          <button
            onClick={handleRetry}
            style={{
              padding: '8px 16px',
              backgroundColor: '#007acc',
              color: 'white',
              border: 'none',
              borderRadius: '6px',
              cursor: 'pointer',
              fontSize: '14px',
            }}
          >
            重试
          </button>
          <button
            onClick={() => {
              // 清除本地存储并重试
              localStorage.clear();
              sessionStorage.clear();
              handleRetry();
            }}
            style={{
              padding: '8px 16px',
              backgroundColor: '#f44336',
              color: 'white',
              border: 'none',
              borderRadius: '6px',
              cursor: 'pointer',
              fontSize: '14px',
            }}
          >
            重置应用
          </button>
        </Box>
      </Box>
    );
  }

  // 主应用界面
  return (
    <Box sx={{ height: '100vh', display: 'flex', flexDirection: 'column' }}>
      <Routes>
        <Route path="/" element={<Layout />}>
          <Route index element={<Navigate to="/connections" replace />} />
          <Route path="connections" element={<ConnectionManager />} />
          <Route path="terminal/:connectionId?" element={<Terminal />} />
          <Route path="tunnels" element={<TunnelManager />} />
          <Route path="settings" element={<Settings />} />
          <Route path="*" element={<Navigate to="/connections" replace />} />
        </Route>
      </Routes>
    </Box>
  );
};

export default App;